﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using MobileBank1.Model;

namespace MobileBank1.Console
{
	public class Ai
	{
		private readonly List<string> _filesList;

		public Ai(List<string> filesList)
		{
			_filesList = filesList;
		}

		public void TryParseFiles()
		{
			foreach (var file in _filesList)
			{
				var fileReader = new FileReader();
				fileReader.OpenFile(file);
				var recordReader = new RecordReader(fileReader);
				var recordConverter = new RecordConverter();

				var raw = recordReader.GetRecord();
				var records = new List<MobileRecord>();
				while (raw.Count > 0)
				{
					var record = new MobileRecord();
					recordConverter.ConevrtHeader(record, raw);
					recordConverter.ConevrtBody(record, raw);
					records.Add(record);
				}

				fileReader.Close();

				var resultPath = Path.ChangeExtension(file, "txt");
				var fs = new StreamWriter(resultPath, false, Encoding.ASCII);
				foreach (var record in records)
				{
					foreach (DataRow row in record.Table.Rows)
					{
						fs.WriteLine(FormatRow(row));
					}
				}
			}
		}

		private string FormatRow(DataRow row)
		{
			return string.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}{0}{9}{0}{10}{0}{11}{0}{12}{0}{13}{0}{14}", 
				"\t",
				row["Phone"],
				row["CardMonitoring"],
				row["Card"],
				row["RegistrationDate"],
				row["Tarif"],
				row["Operator"],
				row["Email"],
				row["Card2"],
				row["Card3"],
				row["Card4"],
				row["Card5"],
				row["Card6"],
				row["Card7"],
				row["Card8"]
				);
		}
	}
}
